//
//  HWGameDetailTableController.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/3/10.
//  Copyright © 2022 94Wan. All rights reserved.
//

import UIKit
import JXPagingView
import ZLPhotoBrowser
class HWGameDetailTableController: HWBaseViewController {
    var gameId = ""
    var listViewDidScrollCallback: ((UIScrollView) -> ())?
    var tableView:UITableView!
    var tableViewProtocol = HWGameDetailTableProtocol()
    var detailModel:HWGameDetailInfoModel = HWGameDetailInfoModel()
    var commentList:[HWGameDetailCommentListModel] = []
    var httpManager = HWGameDetailHttpManager()
    var playerView:CLPlayerView!
    var allButtonClick:(()->())?
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        tableView.delegate = tableViewProtocol
        tableView.dataSource = tableViewProtocol
        tableView.backgroundColor = .colorWithHexString(hexString: "#FFFFFF")
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 40
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        
        initFrame()
        
        addAction()
        
        loadData()
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if self.playerView != nil {
            self.playerView.destroyPlayer()
        }
    }

}
extension HWGameDetailTableController {
    private func initUI() -> Void {
        navigationView.isHidden = true
        self.view.backgroundColor = .white
        view.addSubview(tableView)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.ly_emptyView = LYEmptyView.emptyActionView(withImageStr: "", titleStr: "", detailStr: "暂无数据", btnTitleStr: "点击刷新", btnClick: {
//            self.loadData()
        })
        tableView.ly_emptyView.actionBtnCornerRadius = 15*widthScale
        tableView.ly_emptyView.actionBtnHeight = 30*widthScale
        tableView.ly_emptyView.contentViewOffset = -120*widthScale
        
    }
    
    private func initFrame() -> Void {
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}
extension HWGameDetailTableController:JXPagingViewListViewDelegate {
    func listView() -> UIView {
        return view
    }
    
    func listScrollView() -> UIScrollView {
        return self.tableView
    }
    
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        self.listViewDidScrollCallback = callback
    }
    
}

extension HWGameDetailTableController {
    func loadData() -> Void {
        
        let netGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "GameDetailTable")
        
        netGroup.enter()
        workingQueue.async {
            
            self.httpManager.getGameDetailInfo(gameId: self.gameId) { model in
                self.detailModel = model
                netGroup.leave()
            } failure: { error in
                netGroup.leave()
            }
        }
        
        netGroup.enter()
        workingQueue.async {
            self.httpManager.getGameDetailCommentList(gameId: self.gameId) { models in
                self.commentList = models
                netGroup.leave()
            } failure: { errorString in
                netGroup.leave()
            }
        }
        
        netGroup.notify(queue: workingQueue) {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                self.detailModel.commentList = self.commentList
                self.tableViewProtocol.model = self.detailModel
                self.tableView.reloadData()
            }
            
        }

    }
}

extension HWGameDetailTableController {
    func addAction() -> Void {
        tableViewProtocol.scrollDidScroll = {
            scrollView in
            self.listViewDidScrollCallback?(scrollView)
        }
        
        tableViewProtocol.zanButtonClick = {
            id in
            self.httpManager.getGameDetailCommentZan(id: id) { success in
                self.httpManager.getGameDetailCommentList(gameId: self.gameId) { models in
                    self.commentList = models
                    self.detailModel.commentList = self.commentList
                    self.tableViewProtocol.model = self.detailModel
                    self.tableView.reloadData()
                } failure: { errorString in
                    
                }
            } failure: { errorString in
                
            }

        }
        
        tableViewProtocol.gameImageViewClick = {
            imageView ,model in
            if model.imgs.video.video_url.count > 0 {
                self.playerView = CLPlayerView.init(frame: imageView.frame)
                self.playerView.update { config in
                    config?.topToolBarHiddenType = .small
                    config?.videoFillMode = .resizeAspect
                    config?.autoRotate = false
                }
                self.playerView.url = URL(string:model.imgs.video.video_url)
                imageView.addSubview(self.playerView)
                self.playerView.playVideo()
                self.playerView.endPlay {
                    if self.playerView != nil {
                        self.playerView.destroyPlayer()
                    }
                }
                self.playerView.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
            }else{

            }
        }
        
        tableViewProtocol.jumpToGameDetail = {
            let gameDetail = HWGameDetailController()
            gameDetail.gameId = $0
            self.navigationController?.pushViewController(gameDetail, animated: true)
        }
        
        tableViewProtocol.jumpToCommentDetail = {
            id in
            let sonController = HWGameCommentSonController()
            sonController.id = id
            sonController.gameId = self.gameId
            sonController.releaseCallBack = {
                self.loadData()
            }
            self.navigationController?.pushViewController(sonController, animated: true)
        }
        
        tableViewProtocol.allButtonClick = {
            self.allButtonClick?()
        }
        
        tableViewProtocol.videoPlayClick = {
            url in
            
            let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
                return .video
            } urlImageLoader: { (url, imageView, progress, loadFinish) in
                imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                    let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                    debugPrint("\(percentage)")
                    progress(percentage)
                } completionHandler: { (_) in
                    loadFinish()
                }
            }
            
            vc.doneBlock = { (datas) in
                debugPrint(datas)
            }
            vc.modalPresentationStyle = .fullScreen
            self.showDetailViewController(vc, sender: nil)
        }
        
        tableViewProtocol.endPlay = {
            if self.playerView != nil {
                self.playerView.destroyPlayer()
            }
        }
    }
}
